﻿using System;
using System.Linq.Expressions;
using System.Reflection;

namespace InfiniTec
{
    public static class ExpressionExtension
    {
        public static string GetPropertyName<T, K>(this Expression<Func<T, K>> viewModelPropertySelector)
        {
            if (viewModelPropertySelector.Body.NodeType != ExpressionType.MemberAccess)
            {
                throw new ArgumentException(
                    "A property selector expression has an incorrect format");
            }

            var memberAccess = (MemberExpression)viewModelPropertySelector.Body;

            if (memberAccess.Member.MemberType != MemberTypes.Property)
            {
                throw new ArgumentException("A selected member is not a property");
            }

            return memberAccess.Member.Name;
        }

        public static string GetPropertyName<T>(this Expression<Func<T>> viewModelPropertySelector)
        {
            if (viewModelPropertySelector.Body.NodeType != ExpressionType.MemberAccess)
            {
                throw new ArgumentException(
                    "A property selector expression has an incorrect format");
            }

            var memberAccess = (MemberExpression)viewModelPropertySelector.Body;

            if (memberAccess.Member.MemberType != MemberTypes.Property)
            {
                throw new ArgumentException("A selected member is not a property");
            }

            return memberAccess.Member.Name;
        }

    }
}